package com.bsj.media.init;

import cn.hutool.core.util.StrUtil;
import com.bsj.media.media.gb28181.Gb28181Rtp;
import com.bsj.power.common.util.ExceptionUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yinhao
 * @version 1.0
 * @description 缓存GB28181解析的数据流
 * @date 2024/6/19
 */
@Slf4j
public class Gb28181RtpCachedThread {

    private static Thread thread;

    private static boolean flag = true;

    /**
     * 清除过期时间
     */
    private static long removeExpireDataTime;
    /**
     * key: 终端号_通道号
     */
    private static Map<String, Gb28181Rtp> Gb28181RtpMap = new ConcurrentHashMap<>();

    public static Map<String, Gb28181Rtp> getMap() {
        return Gb28181RtpMap;
    }

    public static void start() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    long time = System.currentTimeMillis();
                    doRun(time);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        log.info("检测GB28181 RTP流");
        thread.start();
    }

    private static void doRun(long curTimeStamps) {
        if (curTimeStamps - removeExpireDataTime > 60 * 1000) {
            try {
                removeExpireDataTime = curTimeStamps;
                long start = System.currentTimeMillis();
                Iterator<Map.Entry<String, Gb28181Rtp>> iterator = Gb28181RtpMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Gb28181Rtp> next = iterator.next();
                    if (Objects.nonNull(next.getValue()) && next.getValue().isExpire(curTimeStamps)) {
                        log.info(StrUtil.format("key={},移除缓存!!", next.getKey()));
                        iterator.remove();
                    }
                }
                long end = System.currentTimeMillis();
                if (end - start > 500) {
                    log.warn(StrUtil.format("删除udpGbServer的打包对象，耗时{}ms", (end - start)));
                }
            } catch (Exception e) {
                log.error("异常: {}", ExceptionUtil.getStackStr(e));
            }
        }
    }

    public static void stop() {
        flag = false;
        if (thread != null) {
            thread.interrupt();
        }
    }
}
